package com.pig4cloud.controller;

import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.constant.enums.ErrorCodeEnum;
import com.pig4cloud.dto.UserLoginDTO;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.entity.UserEntity;
import com.pig4cloud.service.UserService;

import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springdoc.core.annotations.ParameterObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 小程序端用户表
 *
 * @author pig
 * @date 2025-04-09 15:29:15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tbUser" )
@Tag(description = "tbUser" , name = "小程序端用户表管理" )
//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class UserController {

    private final UserService userService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param tbUser 小程序端用户表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
//    @HasPermission("admin_tbUser_view")
    public R getTbUserPage(@ParameterObject Page page, @ParameterObject UserEntity tbUser) {
        LambdaQueryWrapper<UserEntity> wrapper = Wrappers.lambdaQuery();
        return R.ok(userService.page(page, wrapper));
    }


    /**
     * 通过条件查询小程序端用户表
     * @param tbUser 查询条件
     * @return R  对象列表
     */
    @Operation(summary = "通过条件查询" , description = "通过条件查询对象" )
    @GetMapping("/details" )
    @HasPermission("admin_tbUser_view")
    public R getDetails(@ParameterObject UserEntity tbUser) {
        return R.ok(userService.list(Wrappers.query(tbUser)));
    }

	@Inner
	@GetMapping("/{username}")
	public R tbUserInfo(@PathVariable String username) {
		UserEntity user = userService.getOne(Wrappers.<UserEntity>lambdaQuery()
				.eq(UserEntity::getUsername, username));
		return R.ok(user);
	}

    /**
     * 新增小程序端用户表
     * @param tbUser 小程序端用户表
     * @return R
     */
    @Operation(summary = "新增小程序端用户表" , description = "新增小程序端用户表" )
    @SysLog("新增小程序端用户表" )
    @PostMapping
    @HasPermission("admin_tbUser_add")
    public R save(@RequestBody UserEntity tbUser) {
        return R.ok(userService.save(tbUser));
    }

	@PostMapping("/login")
	@Operation(summary = "登录")
	public R<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
		try {
			return R.ok(userService.wxLoginUser(userLoginDTO));
		} catch (WxErrorException e) {
			log.error("登录异常:{}", e.getError().getErrorMsg());
			return R.failed(null, ErrorCodeEnum.ERROR_QUERY.getCode(), e.getError().getErrorMsg());
		} finally {
			WxMaConfigHolder.remove();//清理ThreadLocal
		}
	}

    /**
     * 修改小程序端用户表
     * @param tbUser 小程序端用户表
     * @return R
     */
    @Operation(summary = "修改小程序端用户表" , description = "修改小程序端用户表" )
    @SysLog("修改小程序端用户表" )
    @PutMapping
    @HasPermission("admin_tbUser_edit")
    public R updateById(@RequestBody UserEntity tbUser) {
        return R.ok(userService.updateById(tbUser));
    }

    /**
     * 通过id删除小程序端用户表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除小程序端用户表" , description = "通过id删除小程序端用户表" )
    @SysLog("通过id删除小程序端用户表" )
    @DeleteMapping
    @HasPermission("admin_tbUser_del")
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(userService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param tbUser 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @HasPermission("admin_tbUser_export")
    public List<UserEntity> exportExcel(UserEntity tbUser, Long[] ids) {
        return userService.list(Wrappers.lambdaQuery(tbUser).in(ArrayUtil.isNotEmpty(ids), UserEntity::getId, ids));
    }

    /**
     * 导入excel 表
     * @param tbUserList 对象实体列表
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @HasPermission("admin_tbUser_export")
    public R importExcel(@RequestExcel List<UserEntity> tbUserList, BindingResult bindingResult) {
        return R.ok(userService.saveBatch(tbUserList));
    }
}
